#!/bin/bash
# front server list
servers[1]="tinhnv@10.254.53.244:/home/tinhnv/thethao/server1"
servers[2]="tinhnv@10.254.53.244:/home/tinhnv/thethao/server2"
servers[3]="tinhnv@10.254.53.244:/home/tinhnv/thethao/server3"
# cache configuration
public_dir="/home/tinhnv/tinhnv.thethao.vnexpressdev.net/public"
public_url="http://tinhnv.thethao.vnexpressdev.net"
cache_dir="$public_dir/tin-tuc/"
cache_dir_tmp="$public_dir/tin-tuc-tmp/"
cache_url="$public_url/tin-tuc/"
# gearman configuration
gearman_client=/build/gearmand/bin/gearman
gearman_host=10.254.53.213
gearman_port=4730
gearman_func=vnett_sync_cache

# logic processs
while : ; do
	# listen gearman job
	input=`$gearman_client -w -h $gearman_host -p $gearman_port -N -c 1 -f $gearman_func`
	# parse data	
	data=`echo $input|awk -F\" '{print $2}'`
	if [ -n "$data" ]; then
		separator=":vnett:"
		type=`echo $data|awk -F$separator '{print $1}'`
		url=`echo $data|awk -F$separator '{print $2}'`
		path=`echo $data|awk -F$separator '{print $3}'`
		# generate cache for article		
		pc=`curl -s $url?pc=1`
		#move data to cache tmp
		rsync -avuzr --delete $cache_dir $cache_dir_tmp
		rm -Rf $cache_dir*
		rm -f "$public_dir/index.html"
		# make cache folder and sub folder
		cache_data_dirs=`find $cache_dir_tmp -type d`
		for d in $cache_data_dirs
		do
			echo $d
			d_url=${d//$cache_dir_tmp/$cache_url}
			d_path=${d//$cache_dir_tmp/$cache_dir}
			rs=`curl -s $d_url?pc=1`
			if [ -d "$d_path" ]; then
				echo "Folder exported : $d_url"
			else
				echo "Folder export fail: $d_url"
			fi
		done
		# make cache articles
		cache_data_files=`find $cache_dir_tmp -type f`
		for f in $cache_data_files
		do
			echo $f
			f_url=${f//$cache_dir_tmp/$cache_url}
			f_path=${f//$cache_dir_tmp/$cache_dir}
			rs=`curl -s $f_url?pc=1`
			if [ -f "$f_path" ]; then
				echo "File exported: $f_url"
			else
				echo "File export fail: $f_url"
			fi
		done
		#sync to front server
		pc=`curl -s $public_url?pc=1`
		if [ -f "$path" ]; then
			#sync to front server
			for server in ${servers[*]}
			do
				echo $server
				rsync -avuzr --delete --ignore-errors $cache_dir $server
				if [ -f "$public_dir/index.html" ]; then
					rsync -avuzr --delete --ignore-errors $public_dir/index.html $server
				fi
			done
		fi
		exit
	else
		echo "Waiting job..."
		sleep 10
	fi
done